package com.tduck.cloud.api.util;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.tduck.cloud.common.constant.UipConstant;
import com.tduck.cloud.common.util.RedisUtil;
import com.tduck.cloud.common.util.uip.crypto.SignHelper;
import com.tduck.cloud.common.util.uip.model.AccessTokenResponse;
import com.tduck.cloud.common.util.uip.model.GenericResponse;
import com.tduck.cloud.common.util.uip.model.UipMessageTemplate;
import com.tduck.cloud.common.util.uip.utils.RequestTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 友空间开放平台工具类
 *
 * @author Guard Baby
 * @date 2022/12/26
 */
@Component
@Slf4j
public class UipUtils {

    @Autowired
    private RedisUtil redisUtils;

    public String getAccessToken() {
        //先从缓存中获取
        Object tokenObj = redisUtils.get(UipConstant.TOKEN_KEY);
        if (Objects.nonNull(tokenObj)) {
            return (String) tokenObj;
        }
        Map<String, String> params = new HashMap<>();
        // 除签名外的其他参数
        params.put("appKey", UipConstant.APP_KEY);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        // 计算签名
        String signature = null;
        try {
            signature = SignHelper.sign(params, UipConstant.APP_SECRET);
        } catch (Exception e) {
            log.error("计算签名失败", e);
            return null;
        }
        String requestUrl = UipConstant.GET_TOKEN_URL;
        params.put("signature", signature);
        GenericResponse<AccessTokenResponse> response = null;
        try {
            response = RequestTool.doGet(UipConstant.GET_TOKEN_URL, params, new TypeReference<GenericResponse<AccessTokenResponse>>() {
            });
        } catch (IOException e) {
            log.error("调用uip接口失败", e);
            return null;
        }

        if (response.isSuccess()) {
            AccessTokenResponse accessTokenResponse = response.getData();
            redisUtils.set(UipConstant.TOKEN_KEY, accessTokenResponse.getAccessToken(), accessTokenResponse.getExpire());
            log.info("token对象:{}", JSON.toJSONString(accessTokenResponse));
            return accessTokenResponse.getAccessToken();
        }
        return null;
    }

    public String queryStaffList(int pageIndex, int pageSize, Map<String, Object> paramMap) {
        String token = getAccessToken();
        Map<String, Object> param = new HashMap<>();
        param.put("pageIndex", pageIndex);
        param.put("pageSize", pageSize);
        if (CollUtil.isNotEmpty(paramMap)) {
            param.putAll(paramMap);
        }
        return HttpUtil.post(UipConstant.STAFF_LIST_URL + token, JSON.toJSONString(param));
    }

    public void sendMessage(UipMessageTemplate messageTemplate) {
        sendMessage(UipConstant.SEND_ALARM_MESSAGE_URL, messageTemplate);
    }

    public void sendMessage(String url, UipMessageTemplate messageTemplate) {
        log.info("向友空间发送预警消息：{}", JSON.toJSONString(messageTemplate));
        String result = HttpUtil.post(url + getAccessToken(), JSON.toJSONString(messageTemplate));
        log.info("推送结果：{}", result);
    }

    public String queryYhtId(String code) {
        Map<String, Object> params = new HashMap<>();
        String accessToken = getAccessToken();
        params.put("access_token", accessToken);
        params.put("code", code);
        System.out.println("params = " + params);
        return HttpUtil.get(UipConstant.GET_YHTID_URL, params);
    }

    public String getStaffByYhtUserId(List<String> yhtUserId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", yhtUserId);
        return HttpUtil.post(UipConstant.GET_STAFF_URL + getAccessToken(), JSON.toJSONString(params));
    }

    public String queryOrgTree(String parentOrgId) {
        Map<String, Object> params = new HashMap<>();
        JSONObject externalData = new JSONObject();
        externalData.put("parentorgid", parentOrgId);
        externalData.put("enable", 1);
        params.put("externalData", externalData);
        return HttpUtil.post(UipConstant.QUERY_ORG_TREE + getAccessToken(), JSON.toJSONString(params));
    }

    /**
     * 根据id查询员工详情
     * @param id
     * @return {@code String}
     */

    public String queryHRCStaffDetail(Long id) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        return HttpUtil.post(UipConstant.GET_HR_STAFF_DETAIL_URL + getAccessToken(), JSON.toJSONString(params));
    }
    public String queryPosition(Long postId){
        Map<String, Object> params = new HashMap<>();
        params.put("id", postId);
        params.put("access_token",getAccessToken());
        return HttpUtil.get(UipConstant.POSITION_DETAIL_URL,params);
    }
}

